/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package camara;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/**
 *
 * @author ivan
 */
public class Foscam extends Thread{

    private boolean captura;
    private int muevete;
    private GuiCamara tv;
    private BufferedImage laImagen;
    private int fps;
    private int pulsador;   // 1 -> Encender, 2-> Apagar
    private int modoPulsador;
    private int estadoPulsador;


    // Constantes de la dirección
    final String sCaptura="/snapshot.cgi?";     // Para capturar
    final String sUser="user=";
    final String sPass="pwd=";
    private String sIP;
    private String usuario;
    private String password;
    final String sControl="/decoder_control.cgi?";// Para mover la camara
    final String sControlParameter="command=";  // Que es lo que queremos
    final String sEstado="/get_status.cgi?";
    public Foscam(Object tv, String add,String usr,String pwd){
        captura = false; // No capturamos
        muevete = 0; // No nos movemos
        this.tv = (GuiCamara) tv; // Donde metemos la imagen
        sIP=add;
        this.usuario=usr;
        this.password=pwd;
        this.modoPulsador=1;
        this.estadoPulsador=0;
    }
    public void setModoPulsador(int modo){
        this.modoPulsador=modo;
    }
    public int getAlarmStatus(){
        int datosLeidos;
        int estadoAlarma=0;
        String orden="http://" + this.sIP + this.sEstado +sUser + this.usuario + "&" + sPass + this.password;
        int loPillo;
        byte[] cadena = new byte[512];
        URL url;
        try {
            url = new URL(orden);
            InputStream in;

            try {
                in = url.openStream();
                do{
                    datosLeidos=in.read(cadena);
                }while(datosLeidos>0);
                String lineaLeida = new String(cadena);
                loPillo = lineaLeida.indexOf("alarm_status=");
                if (lineaLeida.charAt(loPillo+13)=='0'){
                    estadoAlarma=0;
                }
                else{
                    estadoAlarma=1;
                }

                in.close();
            } catch (IOException ex) {
                Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
        }

        return estadoAlarma;
    }
    public void setFps(int fps){
        this.fps=fps;
    }
    public void setIP(String ip){
        this.sIP=ip;
    }
    public void setUsuario(String us){
        this.usuario=us;
    }
    public void setPass(String pas){
        this.password=pas;
    }
    //Methods
    public void setCapture(boolean c){
        this.captura=c;
    }
    public boolean getCapture(){
        return this.captura;
    }
    public  void setSube(){
        this.muevete=1;
    }
    public  void setBaja(){
        this.muevete=3;
    }
    public  void setIzquierda(){
        this.muevete=5;
    }
    public void setDerecha(){
        this.muevete=7;
    }
    public int getEstadoRele(){
        
        return this.estadoPulsador;
    }
    public void setRele(int estado){
        if (estado==1){   // Encender
            this.pulsador=1;
        }
        else{   // Apagar
            this.pulsador=2;    // Apagar
        }

    }
    public int getModo(){
        return this.modoPulsador;
    }
    private void CambiaRele(){
        String sActiva, sDesactiva;
        byte[] resp = new byte[64];
        int param;
        int num;
        sActiva = String.format("%d", 94);
        sDesactiva = String.format("%d", 95);
        String ordenActiva = "http://" + this.sIP + this.sControl + this.sControlParameter + sActiva + "&" + sUser + this.usuario + "&" + sPass + this.password;
        String ordenDesactiva = "http://" + this.sIP + this.sControl + this.sControlParameter + sDesactiva+ "&" + sUser + this.usuario + "&" + sPass + this.password;

        try {
            if (this.modoPulsador==1){
                URL url = new URL(ordenActiva);
                InputStream in = url.openStream();
                in.close();
                Thread.sleep(500);  // MEdio segundo entre activaciones
                URL urlpara = new URL(ordenDesactiva);
                InputStream in2 = urlpara.openStream();
                in2.close();
            }
            else{
                if (this.pulsador==1){  // No es modo pulsador...es modo normal...encender
                    URL url = new URL(ordenActiva);
                    InputStream in = url.openStream();
                    in.close();
                    this.estadoPulsador=1;
                }else{  // Apagar
                    URL urlpara = new URL(ordenDesactiva);
                    InputStream in2 = urlpara.openStream();
                    in2.close();
                    this.estadoPulsador=0;
                }
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
        }
        num = 0;

    }

    
    private void DameImagen(String cadena) throws IOException{

        URL url = new URL(cadena);
        this.laImagen = ImageIO.read(url);
    }
    private void Muevete(){
        String sMueve,sPara;
        byte[] resp= new byte[64];
        int num;
        sMueve=String.format("%d",this.muevete-1);
        sPara=String.format("%d",this.muevete);
        String mueve="http://"+this.sIP+this.sControl+this.sControlParameter+sMueve+"&"+sUser+this.usuario+"&"+sPass+this.password;
        String para="http://"+this.sIP+this.sControl+this.sControlParameter+sPara+"&"+sUser+this.usuario+"&"+sPass+this.password;

        try {
            URL url = new URL(mueve);
            InputStream in = url.openStream();
            in.close();
            Thread.sleep(200);  // Esto depende mucho de la red
            URL urlpara = new URL(para);
            InputStream in2 = urlpara.openStream();
            in2.close();
        } catch (InterruptedException ex) {
            Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
                Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
        }
            num=0;      
    }
    //-------------------------------------
    // Esto es el hilo en si..que no pare
    //------------------------------------
    @Override
    public void run(){
        URL url;
        URL url2;
        int i=0;
        int iPasos=0;
        String peticion;
        
        while(true){
            try {
                Thread.sleep(100); // 100mS
                
            } catch (InterruptedException ex) {
                Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (this.muevete!=0){
                this.Muevete();
                this.muevete=0;
                try {
                    peticion="http://"+this.sIP+sCaptura+sUser+this.usuario+"&"+sPass+this.password;
                    url = new URL(peticion);
                    DameImagen(peticion);
                    //
                    this.tv.setImagenLabel1(this.laImagen);
                    //this.tv.jLabel1.setIcon(new ImageIcon(this.laImagen));
                    url=null;
                } catch (IOException ex) {
                    Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            if (this.captura==true){
                if (i==10){
                    i=0;
                    iPasos++;
                    if (iPasos==this.fps){
                        iPasos=0;
                        
                        try {
                            peticion="http://"+this.sIP+sCaptura+sUser+this.usuario+"&"+sPass+this.password;
                            url2=new URL(peticion);
                            DameImagen(peticion);
                            this.tv.setImagenLabel1(this.laImagen);
                            //this.tv.setIcon(new ImageIcon(this.laImagen));
                            url2=null;
                        } catch (IOException ex) {
                            Logger.getLogger(Foscam.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        //this.tv.setIconAlarma(this.getAlarmStatus());
                    }
                }
                i=i+1;
            }
            if (this.pulsador!=0){  // Queremos tocar el rele
                CambiaRele();       // Llamamos a la funcion que lo hace
                this.pulsador=0;    // Marcamos el flag

            }

            
        }

    }
}
